import axios from "axios"
import API from "./index"
import { Message } from "element-ui"

const service = axios.create({
    baseURL: API.baseURL
})

// 添加请求拦截器
service.interceptors.request.use(config => {
    //在发送请求之前做些什么
    if(!config.token){
      let token = localStorage.getItem('token')
      if(token) config.headers.common['token'] = token;
    }
    return config
  },error => {
    // 对请求错误做些什么
    return Promise.reject(error)
  })

//添加响应拦截器
service.interceptors.response.use(function (response) {
    if (response.data.errorMsg) {
        Message.error({
            message: response.data.errorMsg,
            type: 'error',
            duration: 1500
        })
    }
    return response.data
}, function (error) {
    let response = error.response
    switch (response.status) {
        case 400:
            location.href = '#/login'
            Message.error({
                message: response.data.errorMsg || "未知错误",
                type: 'error',
                duration: 1500
            })
            break;
        default:
            Message.error({
                message: response.data.errorMsg || "未知错误",
                type: 'error',
                duration: 1500
            })
            break;
    }
    return Promise.reject(error)
})

export default service